package com.reflect;

import com.domain.Person;
import com.domain.Student;

import java.lang.reflect.Field;

public class ReflectDemo2 {

    public static void main(String[] args) throws Exception {
      //获取class对象
        Class<Person> personClass = Person.class;

        //获取所有public成员变量
        Field[] fields = personClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("====================");
        //获取指定名称public成员变量
        Field no = personClass.getField("no");
        /**
         * 成员变量操作 1设置值 2获取值
         */
        //获取
        Person p = new Person();
        Object o = no.get(p);
        System.out.println(o);
        //设置
        no.set(p,1123);
        System.out.println(p);

        System.out.println("================================");

        /**
         * 获取所有的成员变量,不考虑修饰符
         */
        Field[] declaredFields = personClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        //获取该方法
        Field d = personClass.getDeclaredField("d");
        //忽略安全访问权限.无视private
        d.setAccessible(true);
        Object o1 = d.get(p);
        d.set(p,12341);
        System.out.println(p);
    }
}
